<template>
  <div class="gridnew_gadget_tempalte"
       style="width:100%;height:100%"
       ref="grid-box"
       :id="'a'+id">
    <Portal to="right-disable"
            style="width:100%;height:100%"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill  flex-1"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  style="width:100%;height: 100%;border:0">
        <el-card shadow="never"
                 class="aui-card--fill  flex-1"
                 :style="isHasData ? 'width:100%;height: 100%;border:0;overflow: visible;' : 'width:100%;height: 100%;border:0;overflow: hidden;'">
          <div style="width:100%;height: 100%;overflow: hidden;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="comHeaderIsShow">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :showGridMaxNum="showGridMaxNum"
                           :widgetName="widgetName"></GadgetTitle>
              <div>

                <MoreMenu v-only-clone="$store.getters.botDetail"
                          :slicer='slicer'
                          :fitToHeight='fitToHeight'
                          :gadgetId='id'
                          :gadgetType='gadgetInfo.com'
                          @updateQuery="query"
                          :widgetName="widgetName"
                          :businessType="gadgetInfo.businessType"
                          :id="gadgetInfo.id"
                          @showQueryModel="showQueryModel"
                          @fullScreen="fullScreen" />
              </div>
            </div>
            <div class="control-section"
                 :style="comGridStyle"
                 :class="warpGridClass">
              <div v-if="gadgetSetting.report"
                   class="content-wrapper"
                   style="width:100%;height:100%;"
                   :class="gadgetSetting.report.allowGrouping ? '' : 'showToobar'">
                <BTable :tableData="comTableDataList"
                        :columns="comColumns"
                        ref="myTable"
                        header-row-class-name="el-table__columnheader"
                        :summary-method="getSummaries"
                        :show-summary="showSummary"
                        :conditionFormat="conditionFormat"
                        :startIndex="startIndex"
                        :autoFull="autoFull"
                        :fit="!gadgetSetting.report.autoFit"
                        :gadgetFontSize="gadgetSetting.report.fontsize"
                        :pageFromType="pageFromType"
                        :endIndex="endIndex"
                        :pageConfig="pageConfig"
                        :gadgetHeight="gadgetHeight"
                        @handleTableExport="handleTableExport"
                        @cell-click="tableCellClick"
                        :cell-class-name="tableCellClassName"
                        :gadgetSetting="gadgetSetting"
                        v-if="isHasData && comTableStyle">
                        
                  <el-table-column v-for="column in comColumns"
                                   min-width="10"
                                   :slot="column.field"
                                   header-align="left"
                                   :key="column.field"
                                   :align="getTextAlign(column.textAlign)"
                                   :width="gadgetSetting.report.gridStyle === 'List' ? column.width: ((gadgetSetting.report.autoFit?getColumnWidth(column.field):column.maxWidth))"
                                   :prop="column.field">
                    <template slot="header">
                      <el-tooltip v-if="column.headerTextTooltip"
                                  effect="dark"
                                  :content="column.headerTextTooltip"
                                  placement="right">
                        <span>
                          {{column.headerText?column.headerText:column.field}}
                        </span>
                      </el-tooltip>
                         <!--<ZTooltip :line="1"
                                  v-else
                                 
                                  :content="column.headerText?column.headerText:column.field">
                          <span>{{column.headerText?column.headerText:column.field }}</span>
                        </ZTooltip> -->
                    <span v-else>{{column.headerText?column.headerText:column.field }}</span>
                    </template>
                    <template slot-scope="scope">
                      <component :is="`${findTableTemplateName(column.templateName)}`"
                                 :dataFrom="'Table'"
                                 :curData="scope.row[column.field]"
                                 :curRow="scope.row"
                                 :textAlign="getTextAlign(column.textAlign,'flex')"
                                 :column="column"></component>
                    </template>
                  </el-table-column>
                </BTable>
                <ejs-grid v-else-if="isHasData"
                          :class="{
                              ispagination:$route.path!=='/publicReportPdf'&&gadgetSetting.report.allowPaging,
                              nopagination:!($route.path!=='/publicReportPdf'&&gadgetSetting.report.allowPaging)
                            }"
                          :rowDataBound="rowDataBound"
                          :enableVirtualization="comIsVirtualization"
                          :dataSource="comGridDataList"
                          :queryCellInfo='customiseCell'
                          :pdfQueryCellInfo='exportQueryCellInfo'
                          :gridLines='gadgetSetting.report.gridLines'
                          :allowResizing="gadgetSetting.report.allowResizing"
                          :allowFiltering="gadgetSetting.report.allowFiltering"
                          :filterSettings="gadgetSetting.report.filterSettings"
                          :allowGrouping="gadgetSetting.report.allowGrouping"
                          :allowPaging="gadgetSetting.report.allowPaging"
                          :toolbar="toolbarItem.filter(item=>item!=='ExcelExport')"
                          :allowTextWrap="gadgetSetting.report.allowTextWrap"
                          :textWrapSettings='wrapSettings'
                          :showColumnChooser="gadgetSetting.report.showColumnChooser"
                          :allowReordering="gadgetSetting.report.allowReordering"
                          :allowSorting="gadgetSetting.report.allowSorting"
                          :load="load"
                          :dataBound="dataBound"
                          :pageSettings="gadgetSetting.report.pageSettings"
                          ref="datagrid"
                          :showColumnMenu='gadgetSetting.report.showColumnMenu'
                          :toolbarClick='toolbarClick'
                          :allowExcelExport='gadgetSetting.report.allowExcelExport'
                          :allowPdfExport='gadgetSetting.report.allowPdfExport'
                          :recordClick="recordClick"
                          :sortSettings='sortOptions'
                          :actionComplete='actionCompleteHandler'
                          >
                  <e-columns v-if="gadgetSetting.report.columns && gadgetSetting.report.columns.length > 0">
                    <e-column v-for="(columnItem, index) in gadgetSetting.report.columns"
                              :key="index"
                              :maxWidth="columnItem.maxWidth?columnItem.maxWidth:'auto'"
                              :fieldsNewFormat='columnItem.fieldsNewFormat'
                              :businessType='columnItem.businessType'
                              :isNewPage='columnItem.isNewPage'
                              :fieldsList='columnItem.fieldsList'
                              :fieldsFormat='columnItem.fieldsFormat'
                              :showbymonday='columnItem.showbymonday'
                              :field='columnItem.field'                              
                              :headerText='columnItem.headerText'
                              :autoFit="columnItem.autoFit"
                              :customAttributes="{ class: 'e-attr' }"
                              :sortComparer='""'
                              :textAlign="columnItem.textAlign"
                              :disableHtmlEncode="columnItem.disableHtmlEncode"
                              :headerTemplate='employeetemplate'
                              :headerTextTooltip=columnItem.headerTextTooltip
                              :filter='columnItem.filter'
                              :allowFiltering='columnItem.allowFiltering'
                              :template='formatForGrid[columnItem.templateName]'
                              :direction="columnItem.direction?columnItem.direction:'Descending'"
                              :sortDirection="columnItem.sortDirection ? columnItem.sortDirection : 'Descending'"
                              :visible='columnItem.visible'>
                    </e-column>
                  </e-columns>
                  <e-aggregates v-if="showSummary">
                    <e-aggregate v-for="(item, i) in AggColumn"
                                 :key="i">
                      <e-columns v-if="item && item.length > 0">
                        <e-column v-for="(columnItem, index) in item"
                                  :key="index"
                                  type="Custom"
                                  :field="columnItem.field"
                                  :customAggregate="setCustomFn(columnItem.value)"
                                  :footerTemplate="setTempalte(columnItem.value)">
                        </e-column>
                      </e-columns>
                    </e-aggregate>
                  </e-aggregates>
                </ejs-grid>
                <Pagination v-if="isHasData&&(gadgetSetting.report.allowPaging||(gadgetSetting.report.gridStyle === 'List' && pageFromType !== 'reportLayoutGrid' && !autoFull))" @query="query" v-model="pageConfig"></Pagination>
                <div v-if="!isHasData"
                     class="gadget-no-newdata">
                  <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"
                         :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           v-if="pageFromType!=='reportLayoutGrid'"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :selectFields="selectFields"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />
    <DrillThrough :gadgetId='id'
                  v-if="pageFromType!=='reportLayoutGrid'"
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
    <ExportOptionDialog :exportOptionDialogVisible="exportOptionDialogVisible"
                        :loading="exportGetAllDataLoading"
                        :pages="pageConfig.pages"
                        v-if="pageFromType!=='reportLayoutGrid'"
                        @closeExportOptionDialog="closeExportOptionDialog"
                        @confirmExport="confirmExport"></ExportOptionDialog>
    <export-dialog
        :visible.sync="exportDialog"
        :loading="exportGetAllDataLoading"
        :pages="pageConfig.pages"
        @confirm="gridExport"/>
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import linkFormat from './template/linkFormat'
import boolFormat from './template/boolFormat'
import progessFormat from './template/progessFormat'
import progessFullFormat from './template/progessfullFormat'
import DrillThroughLinkFormat from './template/DrillThroughLinkFormat'
import ticketLinkFormat from './template/ticketLinkFormat'
import timeEntryLinkFormat from './template/timeEntryLinkFormat'
import {DataTransmit} from './template/dataTransmit'
import dateFormat from './template/dateFormat'
import textFormat from './template/textFormat'
import {defaultGadgetSettingList} from '@/utils/data-json'
import {grids} from 'ejs'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import {randomString} from '@/utils'
import {getDrillthrough, hyperLinksTool, isHaveQuotationMarks, returnSqlForFields} from '@/utils/common'
import {exportCvs, exportExcel, exportPdf} from '@/utils/exportPdfCvs'
import ExportOptionDialog from '@/components/export-option-dialog/dialog.vue'
import exportDialog from '@/components/export-option-dialog/export-dialog.vue'
import {destoryDeep} from '@/components/storybook/utilties/destory'
import BTable from '@/components/storybook/b-table/index'
import {debounce, throttle} from 'lodash'
import moment from 'moment'
import {formatFunction} from '@/utils/format'
import ZTooltip from '@/components/storybook/z-tooltip'
import { useTableColumn } from '@/components/storybook/hooks/useTable'

export default {
  inheritAttrs: true,
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { ZTooltip, Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model'), ExportOptionDialog, BTable, exportDialog },
  data () {
    return {
      employeetemplate: function () {
        return {
          template: Vue.component('employeetemplate', {
            template: ` <el-tooltip class="item" effect="dark" :content="$data.data.headerTextTooltip" placement="top-start" v-if="$data.data.headerTextTooltip">
                          <div style="text-align:left">{{$data.data.headerText}}</div>
                        </el-tooltip>
                         <div v-else style="text-align:left">{{$data.data.headerText}}</div>
                        `
          })
        }
      },
      currentTime: null,
      floatNum: 0,
      maxColItem: 0,
      gadgetSetting: {},
      AggColumn: [],
      sumObj: {},
      sumObjFixed: {},
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      dataList: [],
      loading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'gridgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'gridgadget' }).gadgetSetting
        }
      },
      LinkFormat: function () {
        return { template: linkFormat }
      },
      BoolFormat: function () {
        return { template: boolFormat }
      },
      ProgessFormat: function () {
        return { template: progessFormat }
      },
      ProgessfullFormat: function () {
        return { template: progessFullFormat }
      },
      DrillThroughLinkFormat: function () {
        return { template: DrillThroughLinkFormat }
      },
      DateFormat: function () {
        return { template: dateFormat }
      },
      TicketLinkFormat: function () {
        return { template: ticketLinkFormat }
      },
      TimeEntryLinkFormat: function () {
        return { template: timeEntryLinkFormat }
      },
      TextFormat: function () {
        return { template: textFormat }
      },
      conditionFormat: [],
      SumTemplate: function () {
        return {
          template: Vue.component('footerTemplate', {
            template: `<span><span style="font-weight:700;color:#000">{{data.Custom.key}}: </span>{{data.Custom.value}}</span>`,
            data () {
              return { data: {} }
            }
          })
        }
      },
      AverageTemplate: function () {
        return {
          template: Vue.component('footerTemplate', {
            template: `<span><span style="font-weight:700;color:#000">{{data.Custom.key}}: </span>{{data.Custom.value}}</span>`,
            data () { return { data: {} } }
          })
        }
      },
      MinTemplate: function () {
        return {
          template: Vue.component('footerTemplate', {
            template: `<span><span style="font-weight:700;color:#000">{{data.Custom.key}}: </span>{{data.Custom.value}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      MaxTemplate: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span><span style="font-weight:700;color:#000">{{data.Custom.key}}: </span>{{data.Custom.value}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      CountTemplate: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span><span style="font-weight:700;color:#000">{{data.Custom.key}}: </span>{{data.Custom.value}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      toolbarItem: [], // 'ExcelExport'
      wrapSettings: { wrapMode: 'Both' },
      queryId: '',
      queryDrillthrough: {},
      queryDrillthroughList: [],
      selectFields: [],
      widgetName: '',
      linkedDatasetList: [],
      recordNum: 0,
      randomStr: randomString(),
      fxFields: [],
      formatDataList: [],
      isShowCursor: false,
      queryFields: [],
      exportOptionDialogVisible: false,
      exportDialog: false,
      exportGetAllDataLoading: false,
      scrollView: null,
      scrollMaxHeightNum: 0,
      getViewMaxNum: 0,
      allowScroll: false,
      scrollSpeed: 0,
      showGridMaxNum: false,
      showSummary: false,
      argsOrderByList:{},
      sortOptions: {},

      observer: null
    }
  },

  created () {
    // this.query()
    Vue['_this'] = this
    DataTransmit.$on('needData', () => {
      DataTransmit.$emit('giveData', this)
    })
    if(location.pathname.indexOf('bot')!==-1) {
      this.subscribeMessage('runReport', debounce(() => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    }, 2500)) } else {
      this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
      })
    }
    this.$store.state.isWidget = false
  },
  activated () {
    if(this.pageFromType==='reportLayoutGrid'||this.pageFromType==='report'||!this.gadgetSetting.report.autoScroll)return
    if(this.$refs.myTable&&this.$refs.myTable.$refs.tableRef){
      this.$refs.myTable.$refs.tableRef.doLayout()
    }
  },
  mounted() {
    this.getScrollView()
    this.observer = new ResizeObserver(this.resizeHandler);
    const content = this.$refs['grid-box']
    this.observer.observe(content);
  },
  computed: {
    comGridDataList () {
      var retdata = this.autoFull&&this.pageFromType!=='reportLayoutGrid' ? this.dataList.slice(this.startIndex, this.endIndex + 1) : this.dataList
      return retdata
    },
    comIsVirtualization () {
      return !this.autoFull&&this.pageFromType!=='reportLayoutGrid'&&this.comGridDataList.length>100
    },
    comTableDataList () {
      var retdata = this._.cloneDeep(this.dataList)
      return retdata
    },
    comHeaderIsShow () {
      return ((this.widgetName && this.widgetName.trim().length > 0) || (this.gadgetSetting.headerDescription && this.gadgetSetting.headerDescription.trim().length > 0)) && ((this.autoFull ? this.startIndex === 0 : true) || this.startIndex === '0')
    },
    warpGridClass () {
      return this.randomStr
    },
    comColumns () {
      return this.gadgetSetting.report.columns.filter(v => v.visible)
    },
    comTableStyle () {
      return this.gadgetSetting.report && this.gadgetSetting.report.gridStyle !== 'Data Grid'
    },
    comGridStyle () {
      return !this.autoFull ? { margin: '10px', height: 'calc(100% - 52px)' } : this.comHeaderIsShow ? { margin: '0px', height: 'calc(100% - 42px)', width: '100%' } : { margin: '0px', height: '100%', width: '100%' }
    },
    comGridMaxNum () {
      return this.pageFrom==='reportLayout'?(+this.$route.query.comGridMaxNum || 350):0
    },
    autoFit(){
      return this._.get( this.gadgetSetting,'report.autoFit')
    },
 
  },
  watch: {
    editMode (val) {
      if (!val) {
        this.saveGadgetSetting()
      }
    },
  },
  methods: {
    resizeHandler: debounce(function () {
      const content = this.$refs['grid-box']
      if(content){
        useTableColumn(this.dataList || [],this._.get(this.gadgetSetting,'report.columns') || [], {
          fontSize:this._.get(this.gadgetSetting,'report.fontsize') || 14,
          tableWidth: content.clientWidth - 20,
          fontWeight: 400
        })
      }
      this.$forceUpdate()
    }, 80),
   
    handleMouseMove (event) {
      const {clientY,clientX} = event;
      const scrollViewRect = this.scrollView.getBoundingClientRect();
      if(clientX>scrollViewRect.left&&clientX<scrollViewRect.right&&clientY>scrollViewRect.top&&clientY<scrollViewRect.bottom){
        this.stopScroll()
      }else{
        if(!this.allowScroll){
          this.startScroll()
        }
      }
    },
    getScrollView () {
      this.getViewMaxNum++
      if(this.getViewMaxNum>10){
        this.getViewMaxNum=0
        return
      }
      this.scrollView = this.comTableStyle ? document.querySelector(`#a${this.id} .myTable .el-table__body-wrapper`) : document.querySelector(`#a${this.id} .e-content`)
      this.scrollView ? this.autoScroll() : setTimeout(this.getScrollView, 500)
    },
    autoScroll () {
      this.getViewMaxNum=0
      if(this.pageFromType==='reportLayoutGrid'||this.pageFromType==='report'||!this.gadgetSetting.report.autoScroll)return
      document.addEventListener('mousemove', throttle(this.handleMouseMove, 300))
      this.startScroll()
    },
    startScroll () {
      this.allowScroll=true
      this.scrollAnimation()
    },
    stopScroll () {
      this.allowScroll=false
    },
    scrollAnimation () {
      if(!this.allowScroll)return
      this.scrollSpeed++
      if(this.scrollSpeed===parseInt(this.gadgetSetting.report.scrollSpeed)){
        this.scrollSpeed=0
        this.scrollView.scrollTop += 1;
        if (this.scrollView.scrollHeight - this.scrollView.scrollTop === this.scrollView.clientHeight) {
          this.scrollMaxHeightNum++
          if(this.scrollMaxHeightNum===5){
            this.scrollMaxHeightNum=0
            this.scrollView.scrollTop = 0;
          }
        }
      }
      requestAnimationFrame(this.scrollAnimation);
    },
    getAggregatesAlias (key, str) {
      const field = this._.find(this.gadgetSetting.report.columns, { field: key })
      if (field.aggregatesArr) {
        const item = this._.find(field.aggregatesArr, { field: str })
        return item ? item.alias : str
      }
      return str
    },
    getColumnWidth (columnName) {
    
      const curItem=this.gadgetSetting.report.columns.find(v=>v.field===columnName)

      if(curItem&&curItem.maxWidth!=='auto'&&curItem.maxWidth!==''){
        return curItem.maxWidth
      }
      const span=document.createElement('span')
      span.style.position='absolute'
      span.style.visibility='hidden'
      span.style.fontSize=this.gadgetSetting.report.fontsize+'px'
      span.style.top='-9999px'
      span.style.left='-9999px'
      document.body.appendChild(span)
      span.innerText=String(columnName)
      let maxLength = this.formatDataList.reduce((acc, row) => {
        span.innerText=String(row[columnName])
        const length = span.offsetWidth
        return length > acc ? length : acc
      }, span.offsetWidth)
      document.body.removeChild(span)
      return `${maxLength+30}px` 
    },
    isNull (value) {
      if (!value && typeof value !== 'undefined' && value !== 0) {
        return true
      } else {
        return false
      }
    },
    customSumFn: function (dataRes, col) {
      let countLength = this._.sumBy(this.dataList, item => {
        return Number(item[col.field])
      })
      let floatNum = 0
      let num = 0
      let field = this.selectFields.find(iii => iii.alias === col.field)
      if (!field) return '';     
      if (!Number.isInteger(countLength)) { num = countLength.toString().split('.')[1].length }
      if (num < 3) floatNum = num
      else floatNum = 2
      return {
        key: this.getAggregatesAlias(col.field, 'Sum'),
        value: formatFunction(field.businessType, this.toDecimal(countLength, floatNum), field),
      }
    },
    toDecimal (x, m) {
      var val = Number(x)
      if (!isNaN(parseFloat(val))) {
        val = val.toFixed(m)
      }
      return val
    },
    customAggregateFn: function (dataRes, col) {
      let field = this.selectFields.find(iii => iii.alias === col.field)
      if (!field) return '';      
      let point = 2
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        let item = this.gadgetSetting.report.columns[index]
        if (col.field === item.field) {
          point = item.decimalPoint
          break
        }
      }
      return {
        key: this.getAggregatesAlias(col.field, 'Average'),
        value: formatFunction(field.businessType, this.fomatFloat(this._.meanBy(this.dataList, item => Number(item[col.field])), point), field)
      }
    },
    customMinFn: function (dataRes, col) {
      let field = this.selectFields.find(iii => iii.alias === col.field)
      if (!field) return ''
      let min = this._.minBy(this.dataList, col.field)[col.field]
      let point = 2
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        let item = this.gadgetSetting.report.columns[index]
        if (col.field === item.field) {
          point = item.decimalPoint
          break
        }
      }
      return {
        key: this.getAggregatesAlias(col.field, 'Min'),
        value: formatFunction(field.businessType, this.fomatFloat(min, point), field)
      }
    },
    customMaxFn: function (dataRes, col) {
      let field = this.selectFields.find(iii => iii.alias === col.field)
      if (!field) return ''
      let max = this._.maxBy(this.dataList, col.field)[col.field]
      let point = 2
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        let item = this.gadgetSetting.report.columns[index]
        if (col.field === item.field) {
          point = item.decimalPoint
          break
        }
      }
      return {
        key: this.getAggregatesAlias(col.field, 'Max'),
        value: formatFunction(field.businessType, this.fomatFloat(max, point), field)
      }
    },
    customCountFn: function (data, col) {
      let count = this.autoFull?this.dataList.length:grids.getObject('count', data)
      let point = 2
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        let item = this.gadgetSetting.report.columns[index]
        if (col.field === item.field) {
          point = item.decimalPoint
          break
        }
      }
      return {
        key: this.getAggregatesAlias(col.field, 'Count'),
        value: this.fomatFloat(count, point)
      }
    },
    fomatFloat (src, pos) {
      return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos)
    },
    setCustomFn (type) {
      if (type === 'Sum') {
        return this.customSumFn
      } else if (type === 'Average') {
        return this.customAggregateFn
      } else if (type === 'Min') {
        return this.customMinFn
      } else if (type === 'Max') {
        return this.customMaxFn
      } else if (type === 'Count') {
        return this.customCountFn
      }
    },
    setTempalte (type) {
      if (type === 'Sum') {
        return this.SumTemplate
      } else if (type === 'Average') {
        return this.AverageTemplate
      } else if (type === 'Min') {
        return this.MinTemplate
      } else if (type === 'Max') {
        return this.MaxTemplate
      } else if (type === 'Count') {
        return this.CountTemplate
      }
    },
    extractColumn () {
      if (this.autoFull&&this.endIndex!==this.dataList.length) return
      this.maxColItem = 0
      let parentArr = []
      for (let i = 0; i < 5; i++) {
        let itemArr = []
        for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
          let item = this.gadgetSetting.report.columns[index]
          if (item.type === 'number' && item.aggregates.length > 0) {
            this.sumObj[item.field] = item.aggregates
            if (item.aggregates.includes('Average')) this.sumObjFixed[item.field] = item.decimalPoint
            if (this.maxColItem < item.aggregates.length) this.maxColItem = item.aggregates.length
            if (item.aggregates[i]) {
              itemArr.push({
                value: item.aggregates[i],
                field: item.field
              })
            }
          }
        }
        if (itemArr.length > 0) parentArr.push(itemArr)
      }
      this.AggColumn = parentArr
    },
    recordClick (args) {
      if(!args.column) return
      this.queryId = this.selectFields.find(item => item.bind === args.column.foreignKeyField) ? this.selectFields.find(item => item.bind === args.column.foreignKeyField).queryId : ''
        var column = this.selectFields.find(ele => ele.bind === args.column.field)
        if (this.selectFields.some(i => i.dataType === 'measure')) {
          if (!column.dataType) {
            return false
          }
        }
        if (!this.selectFields.some(i => i.dataType === 'dimension')) {
          if (!this.selectFields.some(i => i.dataType === 'measure')) {
            return false
          } else {
          this.queryId = this.selectFields.find(item => item.bind === args.column.foreignKeyField) ? this.selectFields.find(item => item.bind === args.column.foreignKeyField).queryId : ''
          return this.findOriginData('')
        }
        }
        if (column) {
          if (column.businessType === 'hyperlinks') {
            return false
          }
        }
        try {
          if (column.dataType === 'dimension') {
            return false
          }
        } catch (error) {
  
        }
        if (column.dbType !== 'number' && (!column.businessType && column.businessType !== 'number')) {
          if (!args.rowData[args.column.foreignKeyField]) {
            return
          }
        }
        this.findOriginData(getDrillthrough(this.selectFields,args.rowData,args.column.field))
    },
    tableCellClick (rowData, columnData) {
      const rowKey=columnData.label||columnData.property
      this.queryId = this.selectFields.find(item => item.bind === rowKey) ? this.selectFields.find(item => item.bind === rowKey).queryId : ''
      let column = this.selectFields.find(ele => ele.bind === rowKey)
      if (this.selectFields.some(i => i.dataType === 'measure')) {
        if (!column.dataType) {
          return false
        }
      }
      if (!this.selectFields.some(i => i.dataType === 'dimension')) {
        if (!this.selectFields.some(i => i.dataType === 'measure')) {
          return false
        }
        else {
          this.queryId = this.selectFields.find(item => item.bind === rowKey) ? this.selectFields.find(item => item.bind === rowKey).queryId : ''
          return this.findOriginData('')
        }
      }
      if (column) {
        if (column.businessType === 'hyperlinks') {
          return false
        }
      }
      try {
        if (column.dataType === 'dimension') {
          return false
        }
      } catch (error) {

      }
      if (column.dbType !== 'number' && (!column.businessType && column.businessType !== 'number')) {
        if (!rowData[rowKey]) {
          return
        }
      }
      this.findOriginData(getDrillthrough(this.selectFields,rowData,rowKey))

    },
    rowDataBound (args) {
      args.row.childNodes.forEach(item => {
        if (!this.gadgetSetting.report.fontsize) {
          this.gadgetSetting.report.fontsize = 14
        }
        item.style.fontSize = this.gadgetSetting.report.fontsize + 'px'
        item.style.lineHeight = 'normal'
        if (item.dataset.bgc) {
          args.row.style.backgroundColor = item.dataset.bgc
        }
        if (item.dataset.color) {
          args.row.childNodes.forEach(ii => {
            if (!ii.style.color) {
              ii.style.color = item.dataset.color
            }
          })
        }
      })
    },
    exportQueryCellInfo (args) {
      try {
        let findTypeObj = this.selectFields.find(item => item.columnName === args.column.foreignKeyField)
        if (findTypeObj && findTypeObj.columnName === args.column.foreignKeyField && findTypeObj.businessType === 'hyperlinks') {
          let tempValue = args.value ? args.value : ''
          let temp = hyperLinksTool(tempValue, 'gridgadget', args.column.fieldsFormat, args.data, this.selectFields)
          if (temp) {
            args.hyperLink = {
              target: temp,
              displayText: tempValue
            }
          }
        }
      } catch (error) { }
    },
    tableCellClassName ({ row, column,rowIndex }) {
      row.index = rowIndex
      const key=column.label||column.property
      try {
        if (this.isShowCursor) {
          if (key !== 'dimension1') {
            let res = this.selectFields.find(i => {
              return i.bind === key
            })
            if (res.dataType) {
              if (res.dataType !== 'dimension') {
                if (typeof row[key] === 'boolean') {
                  return 'cursor-pointer'
                } else if (Number(row[key]) !== 0) {
                  return 'cursor-pointer'
                } else if (res.businessType === 'number' || res.dbType === 'number') {
                  return 'cursor-pointer'
                }
              }
            }
          }
        }
      } catch (error) {

      }
    },
    customiseCell (args) {
      try {
      const cell = args.cell;
      const request = () => {
        const argsClone = JSON.parse(JSON.stringify(args))
      return () => {
        argsClone.rowData = {}
        argsClone.rowData = argsClone.data
        this.recordClick(argsClone)
      }
      }
    cell.addEventListener('click', request());
    } catch (error) {}
      try {
        if (this.isShowCursor) {
          if (args.column.field !== 'dimension1') {
            let res = this.selectFields.find(i => {
              return i.bind === args.column.field
            })
            if (res.dataType) {
              if (res.dataType !== 'dimension') {
                if (typeof args.data[args.column.field] === 'boolean') {
                  args.cell.classList.add('cursor-pointer')
                } else if (Number(args.data[args.column.field]) !== 0) {
                  args.cell.classList.add('cursor-pointer')
                } else if (res.businessType === 'number' || res.dbType === 'number') {
                  args.cell.classList.add('cursor-pointer')
                }
              }
            }
          }
        }
      } catch (error) {

      }
      try {
        var arr = this.conditionFormat
        var column = args.column.field
        let res = arr.filter(item => {
          if (item.dataForm.filters.rules.length !== 0) {
            return item.dataForm.filters.rules[0].key === column
          }
        })
        if (args.data) {
          res.forEach(it => {
            if (it) {
              let str = ''
              it.dataForm.filters.rules.forEach(ii => {
                if (ii.opt === 'is null'  ) {
                   ii.value = 'is null'
                   ii.opt = '=='
                }
                var val = args.data[ii.key] === null? 'is null' : args.data[ii.key].toString()
                if (ii.type === 'date' || ii.type === 'datetime') {
                  val = moment.tz(val, this.$store.state.user.timezoneId).format('YYYY-MM-DD')
                  let dateRange = ii.valueList && Array.isArray(ii.valueList) ? ii.valueList : []
                  if (dateRange.length) {
                    let operator = it.dataForm.filters.condition === 'and' ? '&&' : '||'
                    if (dateRange.length === 1) {
                      if (dateRange[0].startTime === dateRange[0].endTime) {
                        str += (!str ? '' : operator) + `('${val}' ${ii.opt} '${dateRange[0].startTime}')`
                      } else {
                        if (ii.opt === '==') {
                          str += (!str ? '' : operator) + `('${val}' >= '${dateRange[0].startTime}' && '${val}' <= '${dateRange[0].endTime}')`
                        }
                        if (ii.opt === '!=') {
                          str += (!str ? '' : operator) + `('${val}' < '${dateRange[0].startTime}' || '${val}' > '${dateRange[0].endTime}')`
                        }
                        if (ii.opt === '>') {
                          str += (!str ? '' : operator) + `('${val}' > '${dateRange[0].endTime}')`
                        }
                        if (ii.opt === '>=') {
                          str += (!str ? '' : operator) + `!('${val}' < '${dateRange[0].startTime}')`
                        }
                        if (ii.opt === '<') {
                          str += (!str ? '' : operator) + `('${val}' < '${dateRange[0].startTime}')`
                        }
                        if (ii.opt === '<=') {
                          str += (!str ? '' : operator) + `!('${val}' > '${dateRange[0].endTime}')`
                        }
                      }
                    } else if (ii.opt === '==' || ii.opt === '!=') {
                      let result = ''
                      if (ii.opt === '==') {
                        dateRange.forEach(v => {
                          result += `('${val}' >= '${v.startTime}' && '${val}' <= '${v.endTime}')||`
                        })
                      } else {
                        dateRange.forEach(v => {
                          result += `('${val}' < '${v.startTime}' || '${val}' > '${v.endTime}')&&`
                        })
                      }
                      if (result.substr(-2) === '||' || result.substr(-2) === '&&') {
                        result = result.substr(0, result.length - 2)
                      }
                      str += (!str ? '' : operator) + result
                    } else if (ii.opt === '>') {
                      str += (!str ? '' : operator) + `('${val}' > '${dateRange[dateRange.length - 1].endTime}')`
                    } else if (ii.opt === '>=') {
                      str += (!str ? '' : operator) + `!('${val}' < '${dateRange[0].startTime}')`
                    } else if (ii.opt === '<') {
                      str += (!str ? '' : operator) + `('${val}' < '${dateRange[0].startTime}')`
                    } else if (ii.opt === '<=') {
                      str += (!str ? '' : operator) + `!('${val}' > '${dateRange[dateRange.length - 1].endTime}')`
                    }
                  }
                } else {
                  if (ii.opt === '==' || ii.opt === '!=') {
                    if (!str) {
                      str += `("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                    } else {
                      if (it.dataForm.filters.condition === 'and') {
                        str += `&& ("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                      } else {
                        str += `|| ("${(val).toString()}"   ${ii.opt}   "${(ii.value).toString()}")`
                      }
                    }
                  } else {
                    if (!str) {
                      str += (Number(val) + ii.opt + Number(ii.value))
                    } else {
                      if (it.dataForm.filters.condition === 'and') {
                        str += `&& (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                      } else {
                        str += `|| (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                      }
                    }
                  }
                }
              })
              // eslint-disable-next-line
              let res1 = eval(`${str}`)
              if (res1) {
                if (it.entireRow === 'row') {
                  args.cell.dataset.bgc = it.backgroundColor
                  args.cell.dataset.color = it.textColor
                } else {
                  args.cell.style.color = it.textColor ? it.textColor : '#000000'
                  if (it.formatRadio === 'color' || (it.backgroundColor && !(it.hasOwnProperty('formatRadio')))) {
                    args.cell.style.backgroundColor = it.backgroundColor
                  }

                  if (it.formatRadio === 'icon') {
                    args.data[args.column.field] = it.icon
                  }
                }
              }
            }
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    dataBound (args) {
      this.$emit('gadgetSettingroupSettingsColumns', this.grid.ej2Instances.groupSettings.columns)
      if (!this.isGridInit) {
        this.isGridInit = true
        this.applyGadgetSetting()
      }
    },
    load (item) {
      this.grid = this.$refs.datagrid
      this.gadgetHeight = this.gadgetInfo.h * 20 - 15
    },
    async actionCompleteHandler(args){
      if(args.requestType === 'sorting' && args.target) {
        let sortedColumns = args.columnName
        let order = args.direction? args.direction ==='Ascending' ? 'asc' : 'desc':''
        this.argsOrderByList = args
        this.argsOrderByList.sortedColumns = sortedColumns
        this.argsOrderByList.order = order
        this.query()
      }
    },
    applyGadgetSetting () {
      let columnsList = []
      let isAutofit = false
      // process link column
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        const element = this.gadgetSetting.report.columns[index]
        // add template and drillThrough
        columnsList.push(element.field)       
        if (this.gadgetSetting.report.columns[0] && !this.gadgetSetting.report.columns[0].width) {
          // isAutofit = true
        }

        if (element.templateName && element.templateName === 'linkFormat') {
          this.gadgetSetting.report.columns[index].template = this.LinkFormat
        } else if (element.templateName && element.templateName === 'boolFormat') {
          this.gadgetSetting.report.columns[index].template = this.BoolFormat
        } else if (element.templateName && element.templateName === 'progessFormat') {
          this.gadgetSetting.report.columns[index].template = this.ProgessFormat
        } else if (element.templateName && element.templateName === 'dateFormat') {
          this.gadgetSetting.report.columns[index].template = this.DateFormat
        } else if (element.templateName && element.templateName === 'progessFullFormat') {
          this.gadgetSetting.report.columns[index].template = this.ProgessfullFormat
        } else if (element.templateName && element.templateName === 'ticketLinkFormat') {
          this.gadgetSetting.report.columns[index].template = this.TicketLinkFormat
        } else if (element.templateName && element.templateName === 'timeEntryLinkFormat') {
          this.gadgetSetting.report.columns[index].template = this.TimeEntryLinkFormat
        } else if (element.templateName && element.templateName === 'textFormat') {
          this.gadgetSetting.report.columns[index].template = this.TextFormat
        }
        try {
          if (element.drillThrough && element.drillThrough.status) {
            this.gadgetSetting.report.columns[index].template = this.DrillThroughLinkFormat
          }
        } catch (e) {
        }
        // datetime format bugfix
        if (this.gadgetSetting.report.columns[index].type === 'datetime') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
        if (this.gadgetSetting.report.columns[index].type === 'date') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
      }
      if (isAutofit) {
        columnsList = Object.keys(this.dataList[0])
        this.grid.ej2Instances.autoFitColumns(columnsList)
      }
      this.grid.ej2Instances.setProperties(this.gadgetSetting.report)
      this.$forceUpdate()
    },
    findColumnIndex (arr) {
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index]
        if (element.field === 'Name') {
          return index
        }
      }
      return -1
    },
    saveGadgetSetting () {
      var _self = this
      if (_self.grid) {
        // need edwin look
        var report = JSON.parse(_self.grid.ej2Instances.getPersistData())
        // var nowGridSetting =
        _self._.merge(_self.gadgetSetting.report, report)
        // delete _self.gadgetSetting.report
        // grid table , save obj  from json obj
        // const params = {
        //   gadgetSetting: {
        //     ..._self.gadgetSetting
        //     // report: nowGridSetting
        //   },
        //   gadgetId: this.id
        // }

        // this.$interface.reports.putReportsSettingApi(params).then(({ data: res }) => {
        //   if (res.code !== 0) {
        //     return _self.$message.error(res.msg)
        //   }
        // })
      }
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query(true)
    },
    queryModelPreview () {
      this.query(true)
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = newH * 20 - this.heightoffset - 15
      this.gadgetWidth = newWPx
      if(this.$refs.myTable&&this.$refs.myTable.$refs.tableRef){
        this.$refs.myTable.$refs.tableRef.doLayout()
      }
      // if (!this.gadgetSetting.report.allowPaging) {
      //   let recordNum = document.querySelector(`.gridnew_gadget_tempalte .${this.randomStr} .e-content`).offsetHeight
      //   if (!this.recordNum) this.recordNum = recconfirmExportordNum
      //   document.querySelector(`.gridnew_gadget_tempalte .${this.randomStr} .e-content`).style.height = (this.recordNum + 120) + 'px'
      // }
    },
    toolbarClick (args) {
      this.handleTableExport(args.item.text)
    },
    handleTableExport (key) {
      if ((key === 'Excel Export' || key === 'CSV Export') && this.gadgetSetting.report.showExportOption) {
        this.toolBarExportType = key
        this.exportDialog = true
        return false;
      }
      switch (key) {
        case 'PDF Export':
          if (this.gadgetSetting.report.showExportOption) {
            this.exportOptionDialogVisible = true
          } else {
            exportPdf(this.formatDataList, this.selectFields)
          }
          break
        case 'Excel Export':
          exportExcel(this.formatDataList, this.selectFields)
          break
        case 'CSV Export':
          exportCvs(this.formatDataList, this.selectFields)
          break
      }
    },
    async query (e) {
      let isPaging = false
      this.stopScroll()
      document.removeEventListener('mousemove', this.handleMouseMove)
      try {
        if(!this.$route.path.includes('/publicReportPdf')){
          if (this.isQueryModel && this.isQueryModel()) {
            isPaging = this.dataInfo.gadgetSetting.report.allowPaging || this.dataInfo.gadgetSetting.report.gridStyle === 'List'
          } else {
            const { gadgetSetting } = await this.getWidgetInfo(this.id)
            isPaging = gadgetSetting.report.allowPaging || gadgetSetting.report.gridStyle === 'List'
          }
        }
      } catch (error) {

      }
      if (this.loading) {
        return false
      }
      try {
        if (this.$store.state.bot.botTabsIndex === '3') {
          if (this.id === '739b5811-b832-4e4b-8fab-f4fdff2e6893') {
            return false
          }
        }
      } catch (error) {

      }
      // this.dataList = []
      try {
        this.gadgetSetting.report.columns = []
      } catch (error) { }
      if (e !== 'auto') {
        this.loading = true
        this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      }
      let _self = this
      let obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (let key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      const pageSize=this.$route.path.includes('/publicReportPdf')?{
        size:350,
        current:1
      }:{}
      let param = {
        ...pageSize,
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      _self.queryDrillthrough = {}
      _self.queryDrillthroughList = []
      _self.selectFields = []
      if (this.$refs['datagrid']) {
        destoryDeep(this.$refs['datagrid'])
      }
      if(isPaging) {
        if(this.$route.path !== '/publicReportPdf'){
          param.current = this.pageConfig.current
          param.size = this.pageConfig.pageSize
        }
      }
      if(this.argsOrderByList.sortedColumns){
        param.orderBy = [{alias: this.argsOrderByList.sortedColumns, sort: this.argsOrderByList.order}] 
      }

      this.sortOptions=this.argsOrderByList.sortedColumns?{columns: [{ field: this.argsOrderByList.sortedColumns, direction: this.argsOrderByList.direction }]}:{columns: []}
      const getDataFunction = this.autoFull ? _self.$interface.reports.getReportGridDataInfo : _self.$interface.reports.getReportDataInfo
      this.isHasData = false
      getDataFunction(param)
        .then(({ data: res }) => {
          if(this._.get(this.dataInfo,'gadgetSetting.dynamic',false)){
            res.config =  this.dataInfo.gadgetSetting
          }
    
          _self.conditionFormat = res.conditionFormat.reverse()
          _self.linkedDatasetList = res.datasetSync ? res.datasetSync : []
          _self.verifyHasData(res)
          _self.heightoffset = 5
          _self.gadgetHeight = (_self.gadgetInfo.h * 20) - _self.heightoffset - 15
        
          if (res.config) {
            if(res.data&&res.data.records) {
              res.config.report.pageSettings.pageSize=res.data.size
              res.config.report.pageSettings.pageCount=res.data.pages
              if(this.comGridMaxNum){
                this.showGridMaxNum=res.data.total>350
              }
            }
            if(!isPaging&&!this.autoFull&&this.pageFromType!=='reportLayoutGrid'){
              if(Array.isArray(res.data.records)&&res.data.records.length>100){
                res.config.report.pageSettings.pageSize=this.pageFrom||this.pageFromType?parseInt(_self.gadgetHeight/36*2):30
              }
              if(Array.isArray(res.data)&&res.data.length>100){
                res.config.report.pageSettings.pageSize=this.pageFrom||this.pageFromType?parseInt(_self.gadgetHeight/36*2):30
              }
            }
            
            _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
           
            _self.setfieldsFormat(res.selectFields)
            _self.toolbarItem = _self.gadgetSetting.report.allowGrouping ? _self.gadgetSetting.report.toolbar : []
          }
          if (res.name) {
            _self.widgetName = res.name
          } else if (this.wName) {
            _self.widgetName = this.wName
          } else {
            _self.widgetName = _self.gadgetSetting.headerTitle
          }
          _self.selectFields = res.selectFields
          try {
            _self.isShowCursor = _self.selectFields.some(item => {
              return item.dataType && (item.dataType === 'dimension' || item.dataType === 'measure')
            })
          } catch (error) {

          }
          let objList = []// res.selectFields.find(item => { return item.dataType === 'dimension' })
          for (let i = 0; i < res.selectFields.length; i++) {
            const element = res.selectFields[i]
            if (element.dataType === 'dimension') {
              objList.push(element)
            }
          }
          if (res.fxFields) {
            this.fxFields = res.fxFields
          }
          objList = this._.uniqBy(objList, 'alias')
          if (Array.isArray(objList) && objList.length > 1) {
            _self.queryDrillthroughList = objList
          } else {
            _self.queryDrillthrough = objList[0] || {}
            _self.queryId = _self.queryDrillthrough ? _self.queryDrillthrough.queryId : ''
          }
          _self.isGridInit = false
          // process data
          if (res.data) {

         
            try {
              if(res.data.records) {
                this.pageConfig.total = res.data.total
                this.pageConfig.pages = res.data.pages
                _self.dataList = res.data.records
              }else{
                _self.dataList = res.data
              }
            } catch (error) {
              
            }
            try {
              _self.formatDataList = _self.formatData(JSON.parse(JSON.stringify(_self.dataList)), res.selectFields, 'gridgadget')
              _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
            } catch (error) {

            }
            // _self.dataList = _self.setHyperlinkFormat(res.data, res.selectFields, 'alias', 'gridgadget')
            _self.setColumsFormat(res.selectFields)
            // _self.$refs.datagrid.dataSource = _self.dataList
            _self.extractColumn()
            if(this.pageFromType==='reportLayoutGrid'){
              this.showSummary=this.pageConfig.total<=350
            }else if(this.autoFull){
              this.showSummary=this.endIndex===this.dataList.length&&this.pageConfig.total<=350
            }else{
              this.showSummary=this.AggColumn.length !== 0
            }
          }
          
          _self.isGridInit = false
          if (_self.dataList.length > 0) {
            this.isHasData = false
            if(this.gadgetSetting.report.gridStyle === 'List'){
                this.$nextTick(() => {
                 const content = this.$refs['grid-box']
                  if(content){
                    useTableColumn(this.dataList || [],this._.get(this.gadgetSetting,'report.columns') || [], {
                      fontSize:this._.get(this.gadgetSetting,'report.fontsize') || 14,
                      tableWidth: content.clientWidth - 20,
                      fontWeight: 400
                    })
                  }
                  this.$forceUpdate()
                  this.isHasData = true
                })   
              }else{
                this.$nextTick(() => {
                  this.isHasData = true
                })
            }
          }

          _self.queryFields = res.selectFields

        })
        .catch((error) => {
          if (this.wName) {
            this.widgetName = this.wName
          }
          this.isHasData = false
         
          if (error.response && error.response.status === 504) {
            this.errorStatus = '504'
            this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
          }
        }).finally(() => {
           _self.loading = false
          this.currentTime = new Date()
          this.autoRefreshQuery(e)
          // if(this.comTableStyle){
          //   let columnNum = this.gadgetSetting.report.columns.filter(v => v.visible).length
          //   let width = Math.floor(this.comPageWidth / columnNum)
          //   this.gadgetSetting.report.columns = this.gadgetSetting.report.columns.map(v => {
          //     v.maxWidth = width - 2
          //     return v
          //   })
          // }
          this.$nextTick(() => {
            this.getScrollView()
          })
          if (this.autoFull||this.pageFromType==='reportLayoutGrid') {
            this.gadgetSetting.report.toolbar = []
            this.gadgetSetting.report.allowGrouping = false
            this.gadgetSetting.report.allowPaging = false
            this.gadgetSetting.report.showColumnMenu = false
            this.gadgetSetting.report.allowSorting = false
            this.gadgetSetting.report.allowFiltering = false
            if(this.pageFromType!=='reportLayoutGrid'){
              this.updateGadgetLoadingStatus(true)
            }
            if(this.pageFromType==='reportLayoutGrid'){
              this.$emit('updateTableRowHeight',{
                id:this.id,
                length:this.dataList.length,
                tableType:this.comTableStyle?'table':'grid'
              })
            }
          } else {
            this.updateGadgetLoadingStatus(!this.loading)
          }
          
        })
    },
    destroyed () {
      delete Vue['_this']
      DataTransmit.$off('needData')
    },
    remove () {
      this.close()
      if (this.drop.parentNode) {
        this.drop.parentNode.removeChild(this.drop)
      }
    },
    setfieldsFormat (fieldsList) {
      this.gadgetSetting.report.columns.forEach(item => {
        var res = fieldsList.find(i => {
          return i.bind === item.field
        })
        // if (!res) {
        //   res = fieldsList.find(e => e['dataType'] === 'dimension')
        // }
        // if (!res) {
        //   res = fieldsList.find(e => e['alias'] === 'dimension1')
        // }
        item.fieldsNewFormat = res && res.fieldsNewFormat
        item.fieldsFormat = res && res.fieldsFormat
        item.isNewPage = res && res.isNewPage
        item.showbymonday = res && res.showbymonday
        item.fieldsList = fieldsList
      })
    },
    setColumsFormat (fieldsList) {
      try {
        const autoFit = this._.get( this.gadgetSetting,'report.autoFit')

        this.gadgetSetting.report.columns.forEach(item => {
          let fieldItemIndex = fieldsList.findIndex(e => e['bind'] === item['field'])
          // fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['dataType'] === 'dimension'))
          // fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['alias'] === 'dimension1'))
          if (fieldItemIndex === -1) throw new Error('No Format')
          item.businessType = fieldsList[fieldItemIndex].businessType
          if (item.type === 'number' && fieldsList[fieldItemIndex].businessType === 'number') {
            item.templateName = 'formatNumber'
          } else if ((item.type === 'date' || item.type === 'datetime') && (fieldsList[fieldItemIndex].businessType === 'date' || fieldsList[fieldItemIndex].businessType === 'datetime')) {
            item.templateName = 'formatDate'
          } else {
            let templateName = this.findTemplateName(fieldsList[fieldItemIndex].fieldsFormat, fieldsList[fieldItemIndex].businessType)
            item.templateName = templateName
          }

         
          if(!autoFit){
            item.autoFit= autoFit
            // item.clipMode= 'EllipsisWithTooltip'
          }
        })


      } catch (error) { }
    },
    closeExportOptionDialog () {
      this.exportOptionDialogVisible = false
    },
    async gridExport (exportType) {
      const data = await this.getGridAllData(exportType)
      switch (this.toolBarExportType) {
        case 'Excel Export':
          data.forEach(item => {
            for (const key in item) {
              if (item[key] && item[key].toString().includes('<a')) {
                item[key] = item[key].replace(/[a-zA-z]+:\/\/[\S]*/, val => {
                  if (val[val.length - 1] === '"') {
                    val = val.slice(0, val.length - 1)
                  }
                  return encodeURIComponent(val) + '\"'
                })
              }
            }
          })
          let excelExportProperties = {
            dataSource: data
          }
          if (this.gadgetSetting.report.gridStyle === 'Data Grid' || this.gadgetSetting.report.gridStyle === 'List') {
            this.$refs['datagrid'].excelExport(excelExportProperties)
          } else {
            exportExcel(data, this.selectFields)
          }

          break
        case 'CSV Export':
          exportCvs(data, this.selectFields)
          break
      }
      this.exportDialog = false
    },
    async confirmExport (options) {
      const data = await this.getGridAllData(options.exportData)
      exportPdf(data, this.selectFields, options)
      this.exportOptionDialogVisible = false
    },
    async getGridAllData (exportType) {
      const getAllData = exportType === 'All' && (this.gadgetSetting.report.allowPaging || this.gadgetSetting.report.gridStyle === 'List' )
      if (exportType === 'Current') return this.formatDataList;
      this.exportGetAllDataLoading = true
      let obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (let key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      let param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!getAllData) {
        param.current = Number(exportType)
        param.size = this.pageConfig.pageSize
      }
      const getDataFunction = this.autoFull ? this.$interface.reports.getReportGridDataInfo : this.$interface.reports.getReportDataInfo
      const { data: { data: allData, selectFields } } = await getDataFunction(param)
      this.exportGetAllDataLoading = false
      return this.formatData(JSON.parse(JSON.stringify(param.current ? allData.records : allData)), selectFields, 'gridgadget')
    },
    async gridExport (exportType) {
      const data = await this.getGridAllData(exportType)
      switch (this.toolBarExportType) {
        case 'Excel Export':
          data.forEach(item => {
            for (const key in item) {
              if (item[key] && item[key].toString().includes('<a')) {
                item[key] = item[key].replace(/[a-zA-z]+:\/\/[\S]*/, val => {
                  if (val[val.length - 1] === '"') {
                    val = val.slice(0, val.length - 1)
                  }
                  return encodeURIComponent(val) + '\"'
                })
              }
            }
          })
          let excelExportProperties = {
            dataSource: data
          }
          if (this.gadgetSetting.report.gridStyle === 'Data Grid') {
            this.$refs['datagrid'].excelExport(excelExportProperties)
          } else {
            exportExcel(this.formatDataList, this.selectFields)
          }

          break
        case 'CSV Export':
          exportCvs(data, this.selectFields)
          break
      }
      this.exportDialog = false
    },
    getTextAlign (align = 'left', display = 'block') {
      if(display==='flex'){
        return {
          'left':'flex-start',
          'center':'center',
          'right':'flex-end'
        }[align.toLowerCase()]
      }
      return ['left', 'center', 'right'].includes(align.toLowerCase()) ? align.toLowerCase() : align
    },
    getSummaries (param) {
      let result = []
      const { columns } = param;
      if (!columns.length) return
      columns.forEach((column, index) => {
        const { property } = column;
        if (this.sumObj[property]) {
          const value = this.getResultValue(property, this.dataList, this.sumObj[property], this.sumObjFixed[property]);
          result[index] = this.getJsx(value, property);
        } else {
          result[index] = '';
        }
      })
      return result;
    },
    getResultValue (property, data, keyArr = [], Fixed = 0) {
      let field = this.selectFields.find(iii => iii.alias === property)
      let resultObj = {}
      let sum = data.reduce((c, r) => Number(c) + Number(r[property]), 0)
      let count = data.length
      let min = Math.min(...data.map(v => v[property]))
      let max = Math.max(...data.map(v => v[property]))
      keyArr.forEach(v => {
        switch (v) {
          case 'Sum':
            resultObj.Sum = formatFunction(field.businessType, sum, field)
            break;
          case 'Average':
            resultObj.Average = formatFunction(field.businessType, (sum / count).toFixed(Fixed), field)
            break;
          case 'Min':
            resultObj.Min = formatFunction(field.businessType, min, field)
            break;
          case 'Max':
            resultObj.Max = formatFunction(field.businessType, max, field)
            break;
          case 'Count':
            resultObj.Count = count
            break;

          default:
            break;
        }
      })
      return resultObj
    },
    getJsx (val = {}, property) {
      let result = ""
      const keyArr = Object.keys(val)
      const keyArr2 = Object.keys(val).map(item => {
        return this.getAggregatesAlias(property, item)
      })
      switch (keyArr.length) {
        case 1:
          result = (
            <div>
              <span>{keyArr2[0]}:{val[keyArr[0]]}</span>
            </div>
          )
          break;
        case 2:
          result = (
            <div>
              <span>{keyArr2[0]}:{val[keyArr[0]]}</span>
              <br />
              <span>{keyArr2[1]}:{val[keyArr[1]]}</span>
            </div>
          )
          break;
        case 3:
          result = (
            <div>
              <span>{keyArr2[0]}:{val[keyArr[0]]}</span>
              <br />
              <span>{keyArr2[1]}:{val[keyArr[1]]}</span>
              <br />
              <span>{keyArr2[2]}:{val[keyArr[2]]}</span>
            </div>
          )
          break;
        case 4:
          result = (
            <div>
              <span>{keyArr2[0]}:{val[keyArr[0]]}</span>
              <br />
              <span>{keyArr2[1]}:{val[keyArr[1]]}</span>
              <br />
              <span>{keyArr2[2]}:{val[keyArr[2]]}</span>
              <br />
              <span>{keyArr2[3]}:{val[keyArr[3]]}</span>
            </div>
          )
          break;
        case 5:
          result = (
            <div>
              <span>{keyArr2[0]}:{val[keyArr[0]]}</span>
              <br />
              <span>{keyArr2[1]}:{val[keyArr[1]]}</span>
              <br />
              <span>{keyArr2[2]}:{val[keyArr[2]]}</span>
              <br />
              <span>{keyArr2[3]}:{val[keyArr[3]]}</span>
              <br />
              <span>{keyArr2[4]}:{val[keyArr[4]]}</span>
            </div>
          )
          break;

        default:
          break;
      }
      return result
    }
  },
  beforeDestroy () {
    document.removeEventListener('mousemove', this.handleMouseMove)
  }
}
</script>
<style lang="scss">
// .auto-fit--ellipsis.e-grid.e-wrap .e-rowcell,
// .auto-fit--ellipsis.e-grid.e-wrap .e-columnheader .e-stackedheadercelldiv,
// .auto-fit--ellipsis.e-grid.e-wrap .e-columnheader .e-headercelldiv{
//     white-space:nowrap !important;
//     text-overflow: ellipsis !important;
//     overflow: hidden;
//     div{
//       white-space:nowrap !important;
//       text-overflow: ellipsis !important;
//       overflow: hidden;
//     }
// }

// .auto-fit--ellipsis .cell.el-tooltip{
//    white-space:nowrap !important;
//     text-overflow: ellipsis !important;
//     overflow: hidden;
//     div{
//       white-space:nowrap !important;
//       text-overflow: ellipsis !important;
//       overflow: hidden;
//     }
// }

</style>
<style lang="scss" scoped>
::v-deep .e-rowcell {
  white-space: pre-wrap;
  // padding: 0 12px;
}

.content-wrapper {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 40%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}

::v-deep .e-dlg-content {
  max-height: 130px;
  overflow-y: auto;
}



.gridnew_gadget_tempalte ::v-deep .showToobar .e-grid .e-toolbar {
  display: none;
}

.gridnew_gadget_tempalte ::v-deep .e-grid .e-summarycell {
  font-size: 13px;
  background-color: #f6f6f6;
  border-color: #e0e0e0;
  color: rgba(0, 0, 0, 0.54);
  font-weight: normal;
}

.el-card ::v-deep .el-card__body {
  padding: 0px !important;
  height: 100%;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  // display: flex;
  // justify-content: space-between;
  // align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.e-grid ::v-deep .e-filter-popup {
  max-height: 350px !important;
  // overflow-y: auto;
}

.e-grid ::v-deep .e-checkboxlist {
  height: auto !important;
  overflow-y: visible !important;
}

::v-deep .e-gridcontent.noAllowPaging {
  height: calc(100% - 130px) !important;
  overflow: auto;
}

::v-deep .e-content.noAllowPaging {
  height: calc(100%) !important;
}

::v-deep .e-grid {
  display: flex;
  flex-direction: column;

  .e-gridcontent {
    flex: 1;

    // height: calc(100% - 190px);
    .e-content {
      height: 100% !important;
      overflow: auto !important;
    }
  }
}

::v-deep .e-grid .e-ccdlg .e-cc-contentdiv {
  height: 110px;
  overflow-y: auto;
}
::v-deep .e-gridpager {
  display: none;
}
.ispagination {
  height: calc(100% - 40px)!important;
}
.nopagination {
  height: 100%!important;
}
</style>
